/**
 * 
 */
package com.hk.Mgr.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.customer.CustomerReq;
import com.hk.Mgr.web.message.customer.CustomerRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.SqlFilter;
import com.hk.commons.entity.Customer;
import com.hk.commons.entity.sys.SysUser;
import com.hk.service.sys.ICustomer;
import com.hk.service.sys.ISysUser;

/**
 * @author psx 客户实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/CustomerCtrl")
public class CustomerCtrl extends BaseCtrl {

	@Autowired
	private ICustomer customerService;
	
	@Autowired
	private ISysUser sysUserService;
	
	//销售主管id
	@Value("${role.sellcharge.id}")
	private String sellChargeId;

	/**
	 * @Title: getCustomerById
	 * @Description: 根据id获取系统模块信息
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getCustomerById", method = RequestMethod.POST)
	public ResponseBase<CustomerRes> getCustomerById(
			@RequestBody CustomerReq req) {
		ResponseBase<CustomerRes> resp = new ResponseBase<CustomerRes>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			Customer customer = customerService.findById(req.getId());

			CustomerRes singleResp = new CustomerRes();
			ReqToModelHelper.copyReqValueToModel(customer, singleResp);
			if(customer.getRegisterId()!=null){
				SysUser sysUser=sysUserService.findById(customer.getRegisterId());
				if(sysUser!=null)
					singleResp.setRegisterName(sysUser.getName());
			}
			singleResp.setCreateTime(customer.getCreateTime());
			singleResp.setUpdateTime(customer.getUpdateTime());
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(singleResp);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getCustomerList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getCustomerList", method = RequestMethod.POST)
	public ResponseBase<List<CustomerRes>> getCustomerList(
			@RequestBody CustomerReq req) {
		ResponseBase<List<CustomerRes>> resp = new ResponseBase<List<CustomerRes>>();
		SqlFilter hqlFilter=new SqlFilter("Customer");
		if (StringUtils.isNotBlank(req.getName())) {
			hqlFilter.addEQFilter("name", req.getName());
		}
		if (StringUtils.isNotBlank(req.getIdentity())) {
			hqlFilter.addEQFilter("identity", req.getIdentity());
		}
		hqlFilter.addSort("id");
		hqlFilter.addOrder("desc");
		try {
			//如果登陆人为销售主管，可以看到部门下所有员工登记的客户
			String[] roleIdArr=this.getRoleIds().split(",");
			boolean isSellCharge=false;
			for(int i=0;i<roleIdArr.length;i++){
				if(roleIdArr[i].equals(sellChargeId))
					isSellCharge=true;
			}
			//是销售主管
			if(isSellCharge){
				//先查询所在部门的所有用户getDeptId
				SqlFilter hqlFilter01=new SqlFilter("SysUser");
				hqlFilter01.addLeftJoinINFilter("d.id", " left join Department d on t.deptId=d.id ", this.getDeptId());
				List<SysUser> sysUserList = sysUserService.findBySqlFilter(
						hqlFilter01, 0, 999999);
				String userIds="";
				if(sysUserList!=null&&!sysUserList.isEmpty()){
					for(SysUser su:sysUserList){
						userIds=userIds+su.getId()+",";
					}
					userIds=userIds.substring(0,userIds.length()-1);
				}
				hqlFilter.addLeftJoinINFilter("s.id", " left join SysUser s on t.registerId=s.id ", userIds);
			}else{
				//不是销售主管
				hqlFilter.addEQFilter("registerId",this.getUserId());  //只能看到自己登记的客户信息
			}
			
			List<Customer> customerList = customerService.findBySqlFilter(
					hqlFilter, req.getCurPage(), req.getPageSize());
			
			List<CustomerRes> respList = new ArrayList<CustomerRes>();
			// 根据模块id查询资源
			if (customerList != null && !customerList.isEmpty()) {
				CustomerRes singleResp = null;
				for (Customer customer : customerList) {
					singleResp = new CustomerRes();
					ReqToModelHelper
							.copyReqValueToModel(customer, singleResp);
					if(customer.getRegisterId()!=null){
						SysUser sysUser=sysUserService.findById(customer.getRegisterId());
						if(sysUser!=null)
							singleResp.setRegisterName(sysUser.getName());
					}
					respList.add(singleResp);
				}
			}
			Long total =customerService.countBySqlFilter(hqlFilter).longValue();
			resp.setSize(total);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(respList);

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: saveCustomer
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/saveCustomer", method = RequestMethod.POST)
	public ResponseBase<Customer> saveCustomer(
			@RequestBody CustomerReq req) {
		ResponseBase<Customer> resp = new ResponseBase<Customer>();
		try {
			Customer model = new Customer();
			ReqToModelHelper.copyReqValueToModel(req, model);
			model.setRegisterId(this.getUserId());  //登记id为当前登录人id
			model.setCreateTime( this.getCurrentTime());
			model.setCreator(this.getAccount());
			customerService.add(model);

			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("添加成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: updateCustomer
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/updateCustomer", method = RequestMethod.POST)
	public ResponseBase<Customer> updateCustomer(@RequestBody CustomerReq req) {
		ResponseBase<Customer> resp = new ResponseBase<Customer>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			Customer model = customerService.findById(req.getId());
			ReqToModelHelper.copyReqValueToModel(req, model);
			model.setUpdateTime(this.getCurrentTime());
			model.setUpdator(this.getAccount());
			customerService.update(model);

			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: deleteCustomer
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteCustomer", method = RequestMethod.POST)
	public ResponseBase<Customer> deleteCustomer(@RequestBody CustomerReq req) {
		ResponseBase<Customer> resp = new ResponseBase<Customer>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}

			Customer ret = customerService.delete(req.getId());

			resp.setResult(ret);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("删除成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}
}
